package com.opgea.tutor.servlets;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opgea.tutor.TutorException;
import com.opgea.tutor.domain.qualifiers.TutorDocumentType;
import com.opgea.tutor.service.TutorService;
import com.opgea.tutor.web.dto.TutorDTO;

@Component
@Scope(value="request")
public class ImageServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Autowired
    private TutorService tutorService;

    public ImageServlet() {
	super();
	//tutorService = new TutorServiceImpl();
    }

    protected void doGet(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {

	// long tutorId = Long.valueOf((String)
	// FacesUtil.getParameter("tutorId"));
	long tutorId = Long.valueOf((String) request.getParameter("tutorId"));
	byte[] thumb = null;
	try {
	    TutorDTO tutorDTO = tutorService.find(tutorId);
	    System.out.println("TutorInfo: " + tutorDTO.getFirstName());
	    thumb = tutorService
		    .findDocumentByType(tutorId,
			    TutorDocumentType.PERSONAL_IMAGE.toString())
		    .getFile().getContents();
	} catch (TutorException e1) {
	    e1.printStackTrace();
	}

	String name = "TutorImage";
	response.setContentType("image/jpeg");
	response.setContentLength(thumb.length);

	response.setHeader("Content-Disposition", "inline; filename=\"" + name
		+ "\"");

	BufferedInputStream input = null;
	BufferedOutputStream output = null;

	try {
	    input = new BufferedInputStream(new ByteArrayInputStream(thumb));
	    output = new BufferedOutputStream(response.getOutputStream());
	    byte[] buffer = new byte[8192];
	    int length;
	    while ((length = input.read(buffer)) > 0) {
		output.write(buffer, 0, length);
	    }
	} catch (IOException e) {
	    System.out
		    .println("There are errors in reading/writing image stream "
			    + e.getMessage());
	} finally {
	    if (output != null)
		try {
		    output.close();
		} catch (IOException ignore) {
		}
	    if (input != null)
		try {
		    input.close();
		} catch (IOException ignore) {
		}
	}
    }

    protected void doPost(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
    }

}
